#!/bin/bash
#
#    am-tint2zen: a arcolinux tint2 selection and switcher script
#    Copyright (C) 2015 damo    <damo@bunsenlabs.org>
#    Borrowed with love by arcolinux.

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
#
#   Tint2 config files must be in $TINT2PATH
#
#   When the dialog opens, any running tint2s will be checkmarked.
#
#   Click "OK" and all running tint2s are stopped, and all checkmarked
#   tint2s are started
#
#   To stop a tint2 just uncheck it, and "OK"
#
#   Running tint2s are saved to a session file, and can be run with
#   the "tint2-session" script. To start them at login, add the
#   following line to autostart:
#
#           am-tint2-session
#
########################################################################

TINT2PATH="$HOME/.config/tint2"
SESSIONFILE="$TINT2PATH/tint2-sessionfile"
USAGE="\v\tUSAGE:\n\tWith no command argument, the script uses the chosen
\tTint2 session file \"$TINT2PATH/tint2-sessionfile\",
\tif it exists, otherwise the default tint2rc is used
\v\tTo start them at login, add the following line to autostart:
\v\t\t(sleep 2s && am-tint2-session) &"

### DIALOG VARIABLES
DLGDEC="yad --center --borders=20 "
TITLE="ArcoLinux Tint2 Manager"
WINICON="--window-icon=distributor-logo-arcolinux"
OK="--button=yad-ok:0"
CANCEL="--button=yad-cancel:1"
########################################################################

tintRunning(){
    # make blank tempfile, to save running tint2 paths
    TEMPFILE=$(mktemp --tmpdir tint2.XXXX)
    pgrep -a tint2 | while read pid cmd; do
        if [[ ${cmd%% *} = tint2 ]]; then
            TPATH=$(echo $cmd | awk '{print $NF}')
            echo $TPATH >> $TEMPFILE
        fi
    done
}

fillArrays(){
    num="$1"
    tintsPath[$num]="$2"   # full filepath to the tint2
    tintsArr[$num]="$3"    # displayed name
    # see if name matches one of the running tints
    if grep -qx "$2" "$TEMPFILE";then # if tint2 is running (read from tempfile)
        checkArr[$num]="TRUE"       # make checkmark in dialog
    else
        checkArr[$num]="FALSE"
    fi
}

findTint(){
# search dirs for tint2 config files
    num=0
    for x in $(find $TINT2PATH -type f );do
        # check if likely tint2 config file
        pm=$(grep  "panel_monitor" "$x")
        if [[ $pm ]];then
            TINT2=$( echo $x | awk -F"/" '{print $(NF-1)"/"$NF}')
            fillArrays $num $x $TINT2
            num=$(($num+1))
        fi
    done
}

# get any commandline arguments
if ! (( $# == 0 ));then
    for arg in "$@";do
        if [[ $1 = "-h" ]] || [[ $1 = "--help" ]];then
            echo -e "$USAGE"
            exit 0
        else
            echo -e "\tERROR: sorry I don't understand the input"
            echo -e "$USAGE"
            exit 0
        fi
    done
fi
# get tint2 directories in .tint2, add to array
tintRunning
findTint

# loop through arrays, and build msg text for yad dialog
unset LISTTINT
for ((j=0; j<${#tintsArr[*]}; j++));do
    LISTTINT="$LISTTINT ${checkArr[j]} ${tintsArr[j]}"
done

## Populate dialog from array, get return value(s)
RET=$($DLGDEC $WINICON --list --title="$TITLE" \
    --text="Select Tint2s from the list:" \
    --checklist --width=350 --height=300 \
    --column="Select" --column="tint2 Name" $LISTTINT --separator=":" \
    $OK $CANCEL \
    )

if (( $? == 1 )); then # cancel button pressed
    exit 0
else
    > $SESSIONFILE    # Create new session file
    # loop through returned choices, add to array
    i=0
    OIFS=$IFS   # copy original IFS
    IFS=":"     # separator is ":" in returned choices
    for name in $RET; do
        retTint[$i]=$name
        i=$(($i+1))
    done
    IFS=$OIFS    # reset IFS

    # kill all tint2s
    pgrep -a tint2 | while read pid cmd; do
        if [[ ${cmd%% *} = tint2 ]]; then
            kill "$pid"
        fi
    done

    for name in ${retTint[*]};do       # loop through checkmarked tint2 names
        for ((j=0; j<${#tintsPath[*]}; j++));do  # traverse through elements
            for f in ${tintsPath[j]};do
                display=$( echo $f | awk -F"/" '{print $(NF-1)"/"$NF}')
                # see if it matches the returned name
                if [[ $display = $name ]];then
                    echo -e "$f" >> $SESSIONFILE
                    tint2 -c "$f" &  #start the tint2
                    sleep 1s
                fi
            done
        done
    done
#    am-compositor --restart &   # restart compositor
fi

rm -r $TEMPFILE

exit 0
